<?php
global $m, $tab;
$perms =& $AppUI->acl();
$canViewTaskFee = $perms->checkModuleItem( "taskfee", 'view');
$canEditTaskFee = $perms->checkModuleItem( "taskfee", 'edit');
$canAddTaskLog = $perms->checkModuleItem('task_log', 'add');
$canDeleteTask = $perms->checkModuleItem( "tasks", 'delete');
$canViewExpense = $perms->checkModuleItem('task_expense', 'view');

require_once($AppUI->getModuleClass('companies'));
require_once($AppUI->getModuleClass('suppliers'));
require_once($AppUI->getModuleClass('items'));
require_once($AppUI->getModuleClass('tasks'));
require_once($AppUI->getModuleClass('projects'));
require_once($AppUI->getMasterDataClass('mdtype'));
require_once($AppUI->getMasterDataClass('mdstatus'));
require_once($AppUI->getMasterDataClass('mdcurrency'));

$df = $AppUI->getPref('SHDATEFORMAT');

if (isset($_POST['resetAction'])) {
	$AppUI->unsetPOST('TASK_POST');
}
else {
	if (count($_POST) > 0) {
		$AppUI->savePOST('TASK_POST');
	}
	else {
		$_POST = $AppUI->getPOST('TASK_POST');
	}
}

$AppUI->savePlace();

$page_offset = intval( dPgetParam( $_GET, 'page_offset', 0 ) );
$page_limit = intval( dPgetParam( $_POST, 'page_limit', 10));
$status_id = intval( dPgetParam( $_POST, 'status_id', -1 ) );
$item_type = intval( dPgetParam( $_POST, 'item_type', 0 ) );
$customer = intval( dPgetParam( $_POST, 'customer', 0 ) );
$quotation = intval( dPgetParam( $_POST, 'quotation', -1 ) );
$project_shipping_type = intval( dPgetParam( $_POST, 'project_shipping_type', 0 ) );
$keyword = dPgetParam( $_POST, 'keyword', '' );
$project_name = dPgetParam( $_POST, 'project_name', '' );
$project_code = dPgetParam( $_POST, 'project_code', '' );
$from_date = dPgetParam( $_POST, 'from_date', '' );
$to_date = dPgetParam( $_POST, 'to_date', '' );

//prepair data
$roleAccouting = $perms->userHasRole($AppUI->user_id, "Accounting");
if ($roleAccouting) {
	$status_id = 1;
	$quotation = -2;
}

//do search
$q = new DBQuery();
$q->dropTemp('pitems, wunit, vunit, qunit');
$q->exec();
$q->clear();

$q->createTemp('wunit');
$q->addTable('md_unit');
$q->addQuery('unit_id as wunit_id, unit_name as wunit_name');
$q->exec();
$q->clear();

$q  = new DBQuery;
$q->createTemp('qunit');
$q->addTable('md_unit');
$q->addQuery('unit_id as qunit_id, unit_name as qunit_name');
$q->exec();
$q->clear();

// Volumn Unit
$q  = new DBQuery;
$q->createTemp('vunit');
$q->addTable('md_unit');
$q->addQuery('unit_id as vunit_id, unit_name as vunit_name');
$q->exec();
$q->clear();

$q->createTemp('pitems');
$q->addTable('items');
//$q->leftJoin('wunit', 'wu', 'item_weight_unit = wu.wunit_id');
//$q->leftJoin('qunit', 'qu', 'item_quantity_unit = qu.qunit_id');
//$q->leftJoin('vunit', 'vu', 'item_volume_unit = vu.vunit_id');
if ($item_type > 0) {
	$q->addWhere("item_type1 = $item_type");
}
$q->exec();
$q->clear();

//main query for tasks
$q->addTable('tasks');
$q->innerJoin('projects', 'pro', 'project_id = task_project');
$q->innerJoin('pitems', 'pi', 'item_id = task_item');
$q->leftJoin('md_unit', 'u', 'tasks.task_unit = u.unit_id');
$q->leftJoin('quotations', 'q', 'quote_id = task_quotation ');
if ($project_name != '') {
	$q->addWhere("project_name LIKE '%$project_name%'");
}
if ($project_code != '') {
	$q->addWhere("project_code LIKE '%$project_code%'");
}
if ($keyword != '') {
	$q->addWhere("(item_code LIKE '%$keyword%' or task_name LIKE '%$keyword%')");
}
if ($from_date != '') {
	$q->addWhere("task_end_date >= $from_date");
	$from_date = new CDate($from_date);
}
if ($to_date != '') {
	$q->addWhere("task_end_date <= $to_date");
	$to_date = new CDate($to_date);
}
if ($customer > 0) {
	$q->addWhere("project_company = $customer");
}
if ($quotation != 0) {
	if ($quotation == -1) {
		$q->addWhere('(task_quotation IS NULL or task_quotation = 0)');
	}
	else if ($quotation == -2) {
		$q->addWhere('task_quotation > 0');
	}
	else {
		$q->addWhere("task_quotation = $quotation");
	}
}
if ($status_id == 1) {
	$q->addWhere("task_is_complete=$status_id");
} else if ($status_id == 2) {
	$q->addWhere("task_is_complete <> 1");
}
$needCheckCostCenter = $perms->userHasRole($AppUI->user_id, "FFIA_Staff") || $perms->userHasRole($AppUI->user_id, "Operation");
if ($needCheckCostCenter) {
	$q->addWhere("task_costcenter = {$AppUI->user_costcenter}");
}
$q->addOrder('task_project, task_start_date desc, task_name');
$q->setLimit($page_limit, $page_offset);
$qTotal = $q->prepare();
$q->addQuery('distinct tasks.*, pro.*, q.*, pi.*, u.unit_name');
$tasks = $q->loadList();
/**
 *	TODO: Autocompleter
 */
//$loadStatus = dPgetParam($_POST, 'ajaxLoad', $_GET['ajaxLoad']);
//if($loadStatus){
//	$format = dPgetParam($_POST, 'format', $_GET['format']);
//	$keyword = dPgetParam($_POST, 'keyword', $_GET['keyword']);
//	if(''!=$keyword){
//		$result = array();
//		$tmp = null;
//		// Add link to link
//		for($i = 0; $i < count($tasks); $i++){
//			$tmp = new stdClass();
//			$tmp->id = $tasks[$i]['task_id'];
//			$tmp->code = '[' .$tasks[$i]['reference_code']. '] ';
//			$tmp->name = $tasks[$i]['task_name'];
//			$tmp->link = 'index.php?m=tasks&a=view&task_id='.$tasks[$i]['task_id'];
//			$result[$i] = $tmp;
//		}
//		//if(extension_loaded('json')){
//			echo json_encode($result);
//		//}
//	}
//	echo '';exit;
//}


// Load Object Status
$objMD = new CMdStatus();
$statList = array("" => "", 2 => "Open", 1 => "Completed");

$objMD = new CMdType();
$itemtypeList = $objMD->getTypeList('ItemType1');

$objMD = new CCompany();
$cusList = $objMD->getAllowedRecords($AppUI->user_id, 'company_id, company_name', 'company_name');
$cusList = arrayMerge(array('0'=>"" . $AppUI->_(''). ""), $cusList);

$quotationStatusList = array(0 => 'All', -1 => 'Not link', -2=>'Link');

$curArr = getCurrencyList();
?>
<form name="taskFrm" action="?m=<?=$m?>&tab=<?=$tab?>" method="post">
<input type="hidden" name="offset">
<table cellspacing="0" cellpadding="2" border="0" width="100%" class="infopanel">
<tr>
	<td align="right" nowrap="nowrap">&nbsp;&nbsp;<?=$AppUI->_('From date')?></td>
	<td nowrap="nowrap">
		<input id="idDateFrom" type="hidden" name="from_date"
				value="<?=$from_date ? $from_date->format( FMT_TIMESTAMP_DATE ) : ''?>" />
		<input id="idDateFromD" type="text"  maxlength="10" size="10"
				value="<?=$from_date ? $from_date->format( $df ) : ''?>"
				class="text" />
		<img id="idDateFromB" src="images/calendar.gif" title="<?=$AppUI->_('Calendar')?>" border="0">
	</td>
	<td align="right" nowrap="nowrap">&nbsp;&nbsp;&nbsp;<?=$AppUI->_('Item type')?></td>
	<td width="80%"><?= arraySelect($itemtypeList, 'item_type', ' id="item_type" size="1" class="text" style="width: 143px;"', $item_type, true)?></td>
</tr>
<tr>
	<td align="right"> <?=$AppUI->_('To date')?></td>
	<td>
		<input id="idDateTo" type="hidden" name="to_date"
				value="<?=$to_date ? $to_date->format( FMT_TIMESTAMP_DATE ) : ''?>" />
		<input id="idDateToD" type="text" maxlength="10" size="10"
				value="<?=$to_date ? $to_date->format( $df ) : ''?>"
				class="text" />
		<img id="idDateToB" src="images/calendar.gif" title="<?=$AppUI->_('Calendar')?>" border="0">
	</td>
	<td align="right"> <?=$AppUI->_('Status')?></td>
	<td >
		<?= arraySelect($statList, 'status_id', ' id="idStatus" size="1" class="text" style="width: 143px;"', $status_id, true)?>
	</td>
</tr>
<tr>
	<td align="right"><?=$AppUI->_('Customer')?></td>
	<td colspan="3"><?= arraySelect($cusList, 'customer', ' id="customer" size="1" class="text" style="width: 320px;"', $customer, true)?></td>
</tr>
<tr>
	<td align="right"><?=$AppUI->_('Quotation')?></td>
	<td colspan="3"><?= arraySelect($quotationStatusList, 'quotation', ' id="quotation" size="1" class="text" style="width: 320px;"', $quotation, true)?></td>
</tr>
</table>
<table cellspacing="0" cellpadding="6" border="0" width="100%" class="subinfopanel">
<tr>
	<td>
		<input class="button" type="submit" name="searchAction" value="<?=$AppUI->_('Search');?>"/>
		<input class="button" type="submit" name="resetAction" value="<?=$AppUI->_('reset');?>"/>
	</td>
</tr>
</table>
</form>
<table id="idTasksList" class="list" cellspacing="0" cellpadding="2" border="0" width="100%">
	<tr class="<?=($i % 2 == 0) ? "second" : "first" ?>">
		<th>&nbsp;</th>
		<th>&nbsp;</th>
		<th align="right"><?=$AppUI->_('%')?></th>
		<th ><?=$AppUI->_('Code')?></th>
		<th ><?=$AppUI->_('Name')?></th>
		<th ><?=$AppUI->_('Quotation')?></th>
		<?php if ($canViewExpense):?>
		<th ><?=$AppUI->_('Expense Amount')?></th>
		<?php endif;?>
		<?php if ($canViewTaskFee)
			echo "<th >". $AppUI->_('Sales Amount'). "</th>"
		?>
		<th><?=$AppUI->_('Quantity')?></th>
		<th><?=$AppUI->_('Unit')?></th>
		<!--
		<th ><?=$AppUI->_('Quantity')?></th>
		<th ><?=$AppUI->_('Weight')?></th>
		<th ><?=$AppUI->_('Volume')?></th>
		-->
		<th ><?=$AppUI->_('Start date')?></th>
		<th ><?=$AppUI->_('End date')?></th>
		<th ><?=$AppUI->_('Remarks')?></th>
		<?php if ($canDeleteTask): ?>
		<th ><?=$AppUI->_('Delete')?></th>
		<?php endif;?>
	</tr>
<?php
if (is_array($tasks) && count($tasks) > 0) {
	$totalRows = 0;
	$qTotal = str_ireplace('select *', 'select count(*) as total_rows', $qTotal);
	$tmp = db_loadList($qTotal);
	$totalRows = $tmp[0]['total_rows'];

	require_once($AppUI->getLibraryClass('codeigniter/pagination'));
	$pagination = new CI_Pagination();
	$config = array(
		'base_url' => "?m=$m&tab=$tab",
		'total_rows' => $totalRows,
		'per_page' => $page_limit,
		'cur_tag_open' => "<u>",
		'cur_tag_close' => "</u>"

	);
	$pagination->initialize($config);
	?>

	<script type="text/javascript">
		function submitForm(offset) {
			document.reportFrm.offset.value = offset;
			document.reportFrm.submit();
		}
	</script>
	<?
	$i = 0;
	$lastProject = 0;
	foreach ($tasks as $row) {
		$my_cc_task = $needCheckCostCenter ? $row['task_costcenter'] == $AppUI->user_costcenter : TRUE;
		$i++;
		$start_date = new CDate($row['task_start_date']);
		$end_date = new CDate($row['task_end_date']);
		if ($lastProject != $row['task_project']) {
			$referenceURL = "?m=projects&a=view&project_id=" . $row['task_project'];
	?>
		<tr class="<?=($i % 2 == 0) ? "second" : "first" ?>">
			<td colspan="7">
				<a href="<?=$referenceURL?>" style="border: 1px outset rgb(238, 238, 238); background-color: rgb(255, 255, 255); padding: 3px;"><b><?=$row['project_name']?></b></a>
			</td>
			<td>
				<?=$curArr[$row['project_currency']]?>
			</td>
			<td colspan="100%">&nbsp;</td>
		</tr>
	<?php
			$lastProject = $row['task_project'];
			$i++;
		}
		?>
		<tr class="<?=($i % 2 == 0) ? "second" : "first" ?>" >
			<td align='center'>
				<?
					if ($canAddTaskLog && $my_cc_task && $row['task_is_complete']<1) {
						showIconLink('images/add_log.gif', '?m=timecard&a=vw_newlog&project_id=' . $row['task_project'] . '&task_id=' . $row['task_id'], 'Edit');
					}
					else {
						showIconLink('images/noadd_log.gif', 'js:doShowTaskLog('.$row['task_id'].','.$row['task_log_id'].',0)', 'View');
					}
				?>
				<!--a href="?m=timecard&a=vw_newlog&project_id=<?=$row['task_project']?>&task_id=<?=$row['task_id']?>"><image src="images/add_log.gif" border="0" alt="Add log"/></a-->
			</td>
			<td align='center' onClick="showTask(<?=$row['task_id']?>)">
				<?
					if ($perms->checkModuleItem('tasks', 'edit', $row['task_id']) && $my_cc_task && $row['task_is_complete']<1) {
				?>
						<a href="?m=tasks&a=simpleaddedit&task_id=<?=$row['task_id']?>"><image src="images/edit.gif" border="0" alt="Edit"/></a>
				<?
					}
					else {
				?>
						<a href="?m=tasks&a=view&task_id=<?=$row['task_id']?>"><image src="images/view.gif" border="0" alt="Edit"/></a>
				<?
					}
				?>
				<!--a href="?m=tasks&a=simpleaddedit&task_id=<?=$row['task_id']?>"><image src="images/edit.gif" border="0" alt="Edit"/></a-->
			</td>
			<td align='right' onClick="showTask(<?=$row['task_id']?>)"><?=$row['task_percent_complete']?>%</td>
			<td onClick="showTask(<?=$row['task_id']?>)" ><?=$row['item_code']?></td>
			<td onClick="showTask(<?=$row['task_id']?>)" ><?=$row['task_name']?></td>
			<td onClick="showTask(<?=$row['task_id']?>)" ><?=$row['quote_name']?></td>
			<?php
				if ($canViewTaskFee){
					echo "<td nowrap='nowrap'>";
					if ($canEditTaskFee && $row['task_is_complete'] == 1) {
						echo "<div style='float:left'>";
						showIconLink('images/edit.gif', 'js:return openSalesAmountDialog('.$row['task_id'].', '. $row['task_fee'] . ', \''. addslashes($row['task_name']) .'\')', 'Edit');
						echo "</div>";
					}
					echo "<div style='float:right'>" . currencyFormat($row['task_fee'], $row["project_currency"]) . "</div>";
					echo "</td>";
				}
			?>
			<td onClick="showTask(<?=$row['task_id']?>)" align='right'><?=number_format($row['task_figure'], 0)?></td>
			<td onClick="showTask(<?=$row['task_id']?>)" align='right'><?=$row['unit_name']?></td>
			<?php
			/*
			<td onClick="showTask(<?=$row['task_id']?>)" align='right'><?=$row['qunit_name']?></td>
			<td onClick="showTask(<?=$row['task_id']?>)" align='right'><?=$row['wunit_name']?></td>
			<td onClick="showTask(<?=$row['task_id']?>)" align='right'><?=$row['vunit_name']?></td>
			*/?>
			<td onClick="showTask(<?=$row['task_id']?>)" >
				<div style="float:left"><?=$start_date->format($df)?></div><br/>
				<div style="float:right"><?=@$row['task_start_time']?></div>
			</td>
			<td onClick="showTask(<?=$row['task_id']?>)" >
				<div style="float:left"><?=$end_date->format($df)?></div><br/>
				<div style="float:right"><?=@$row['task_end_time']?></div>
			</td>
			<td onClick="showTask(<?=$row['task_id']?>)" ><?=$row['task_description']?></td>
			<?php if($canDeleteTask && $row['task_is_complete'] < 1 && $my_cc_task) {
			echo "<td align='center'>";
				showIconLink('images/delete.gif', 'js:doDeleteTask('.$row["task_id"]. ', \''.addslashes($row["task_name"]).'\')', 'Delete');
			echo "</td>";
			} else {
				echo "<td>&nbsp;</td>";
			}
			?>
		</tr>
		<?
	}
	?>
	</table>
	<table cellspacing="0" cellpadding="6" border="0" width="100%" class="list">
	<tr>
		<th colspan="100%"><?=$pagination->create_links();?></th>
	</tr>
	</table>

	<?
} else {
	showEmptyRow('1', 'second', 'Not found any references', '100%');
}

?>
</table>
<script>
	Calendar.enabled = true;

	Table("idTasksList").setNormalHover(1);

	function showTask(id)
	{
		location.href = "index.php?m=tasks&a=view&task_id=" + id;
	}

	function doDeleteTask(id, name)	{
		if (confirm( "Do you want to delete "+ name)) {
			$('idTaskId').value = id;
			f = $('MdFormDeleteTask');
			f.del.value = id;
			f.submit();
		}
	}
</script>
<form name="MdFormDeleteTask" id="MdFormDeleteTask" action="?m=tasks" method="post">
	<input type="hidden" name="dosql" value ="do_delete" />
	<input type="hidden" id="idTaskId" name="task_id" value ="" />
	<input type="hidden" name="del" value ="" />
</form>
<?php if($canEditTaskFee):?>
<div id="idSalesAmountDialog" class="popup" style="width: 200px; visibility: hidden; display: none;">
	<form action="?m=tasks&a=do_edit_salesamount" method="POST">
	<input type="hidden" name="task_id" id="saTaskId" value=""/>
	<table width="100%" cellspacing="0" cellpadding="4" border="0" class="subinfopanel">
		<tr>
			<th colspan="2" id="saTaskName">Sales amount</th>
		</tr>
		<tr>
			<td align="right" nowrap="nowrap"> * <?=$AppUI->_( 'Sales amount' )?></td>
			<td nowrap="nowrap">
				<input id="idSalesAmountInput" name="sales_amount_input" type="text" style="width: 80px; text-align: right" value="<?=@$obj->project_actual_budget?>"/>
			</td>
		</tr>
		<tr>
			<td colspan="100%">
				<input type="submit" value="<?=$AppUI->_('Save')?>" name="btnSave"/>
				<input type="button" value="<?=$AppUI->_('Cancel')?>" name="btnCancel" onclick="Dialog('idSalesAmountDialog').hide();"/>
			</td>
		</tr>
	</table>
	</form>
</div>
<?php endif;?>